<?php
/**
 * @software         [JiJinCMS]
 * @author           [上海集锦信息科技有限公司]
 * @website          [http://www.jijinweb.com]
 * @email            [sunny@jijinweb.com]
 **/

namespace app\admin\controller;

use think\facade\View;
use think\facade\Db;
use think\facade\Request;

class Table extends \app\admin\controller\Admin
{
    public function __construct(\think\App $app)
    {
        parent::__construct($app);
        $this->model = new \app\admin\model\TableModel();
        $this->validate = new \app\admin\validate\TableValidate();
    }

    public function index()
    {
        $listRows = Request::param("listRow") ? Request::param("listRow") : config("app.page_show_line");//每页显示多少条
        $data = $this->model->order('sort asc,table_id desc')->paginate(['list_rows' => $listRows, 'query' => request()->param()]);
        // 获取分页显示
        $pagelist = $data->render();
        View::assign("data", $data);
        View::assign("pagelist", $pagelist);
        return View::fetch();
    }

    //更新排序
    public function updateSort()
    {
        $table_id = Request::param('table_id');
        $sort = Request::param('sort');
        foreach ($table_id as $key => $v) {
            $this->model->update(['table_id' => $table_id[$key], 'sort' => $sort[$key]]);
        }
        $this->success("设置成功");
    }

    public function add()
    {
        if (request()->isPost()) {
            $data = $this->request->param();
            if (!$this->validate->check($data)) {
                $this->error($this->validate->getError());
            }
            $this->model->save($data);
            $lastId = $this->model->table_id;
            $this->model->createTable();//创建数据表
            $this->model->createTableFieldHtml();//创建htmlcode
            $this->UserLogModel->add(Request()->action(), $this->model->getName(), $lastId, $this->request->param());
            $this->success("添加成功");
        } else {
            return View::fetch();
        }
    }

    public function update()
    {
        if (request()->isPost()) {
            $data = $this->request->param();
            //编辑状态下重置规则
            $this->validate->rule['name']['unique'] = 'table,name,' . Request::param('table_id', 0, "intval");
            $this->validate->rule['table_name']['unique'] = 'table,table_name,' . Request::param('table_id', 0, "intval");
            $this->validate->append('table_id', 'require');
            $this->validate->remove('table_name', 'checkTable');
            if (!$this->validate->check($data)) {
                $this->error($this->validate->getError());
            }
            //更新表
            $this->model->updateTable($data);
            //
            $this->UserLogModel->add(Request()->action(), $this->model->getName(), $data["table_id"], $this->request->param());
            $this->success($data);

        } else {
            $table_id = Request::param('table_id');
            $r = $this->model->find($table_id);
            View::assign("r", $r);
            return View::fetch();
        }
    }

    //删除数据表
    public function delete()
    {
        $table_id = Request::param('table_id');
        if (empty($table_id)) {
            $this->error("id不存在!");
        }
        $data = $this->model->find($table_id);
        if (!$data) {
            $this->error("数据表不存在!");
        }
        //检查该表下是否有模型，有模型禁止删除（防止误操作）
        $model = Db::name("model")->where("table_id", $table_id)->find();
        if ($model) {
            $this->error("该数据表下有模型，请先删除模型!");
        }
        //检查新表名是否存在（如果存在需要验证该表里是否有数据）
        if (table_exists("cms_" . $data['table_name'])) {
            $count = Db::name("cms_" . $data['table_name'])->count();
            if ($count) {
                $this->error("该模型下有数据，请先删除数据！");
            }
        }
        //删除记录
        $this->model->where("table_id", $table_id)->delete();
        //删除所有和这个表相关的字段
        Db::name("table_field")->where("table_id", $table_id)->delete();
        //删除主表
        $this->model->drop_table("cms_" . $data['table_name']);
        //删除副表
        $this->model->drop_table("cms_" . $data['table_name'] . "_data");
        //
        $this->UserLogModel->add(Request()->action(), $this->model->getName(), $table_id, $this->request->param());
        $this->success("删除成功");
    }

    public function redundancy()
    {
        //查询现有的所有catid
        $catids = Db::name('cat')->column('catid');
        $table_name = Request::param('table_name');
        $table_id = Request::param('table_id');
        //查询该表中所有冗余数据
        $data = Db::name('cms_' . $table_name)
            ->alias('t')
            ->join('user u', 't.userid=u.user_id')
            ->whereNotIn('t.catid', $catids)
            ->field('t.id,t.catid,t.title,t.newstime,u.username')
            ->select();
        View::assign("data", $data);
        View::assign("table_name", $table_name);
        View::assign("table_id", $table_id);
        return View::fetch();
    }

    public function redundancy_view()
    {
        $table_name = Request::param('table_name');
        $id = Request::param('id');
        $r = Db::name('cms_' . $table_name)->where('id',$id)->find();
        $r['username'] = Db::name('user')->where('user_id',$r['userid'])->field('username')->find();
        View::assign("r", $r);
        return View::fetch();
    }

    public function redundancy_update()
    {
        if(request()->isPost()){
            $data = Request::param();
            $edit['title'] = $data['title'];
            $edit['newstime'] = strtotime($data['newstime']);
            $result = Db::name('cms_' . $data['table_name'])->where('id',$data['id'])->save($edit);
            $this->success('修改完成');
        }else{
            $table_name = Request::param('table_name');
            $id = Request::param('id');
            $r = Db::name('cms_' . $table_name)->where('id',$id)->find();
            $r['table_name'] = $table_name;
            $r['username'] = Db::name('user')->where('user_id',$r['userid'])->field('username')->find();
            View::assign("r", $r);
            return View::fetch();
        }
    }

    //删除数据表
    public function redundancy_delete()
    {
        $ids = Request::param('ids');
        $table_name = Request::param('table_name');
        if (empty($ids)){
            $this->error('请选择要删除的选项');
        }
        $result = Db::name('cms_' . $table_name)->where('id','in',$ids)->delete();
        $this->success("删除成功");
    }

    //移动信息
    public function move(){
        if(request()->isPost()){
            $ids = Request::param("ids");
            if (!$ids) {
                $this->error("请选择信息");
            }
            $catid = Request::param("target_catid", "intval", 0);
            if (!$catid) {
                $this->error("请选择目标栏目");
            }
            $table_name = Request::param("table_name");
            $edit = array();
            foreach (explode(',',$ids) as $v){
                $edit['catid'] = $catid;
                $result[] = Db::name('cms_' . $table_name)->where('id',$v)->save($edit);
            }
            $this->updateInfoNum($catid,$table_name);
            $this->UserLogModel->add(Request()->action(),"cms_".$this->ModelInfo["table_name"],$ids,$this->request->param());
            $this->success("操作成功");
        }else{
            if (empty(Request::param("ids"))){
                $this->error('请选择目标数据');
            }
            View::assign("cat",$this->selfModelCat('','',Request::param()));
            View::assign("catid",Request::param("catid",0,"intval"));
            View::assign("ids",Request::param("ids"));
            View::assign("table_name",Request::param("table_name"));
            return View::fetch();
        }
    }

    //整站所有相同模型的栏目（用在 信息移动，复制页面里的）
    private function selfModelCat($pid=0,$str="",$param){
        $where["pid"]=0;
        $where["status"]=1;
        $modelid = Db::name('cms_' . $param['table_name'])->where('id','in',$param['ids'])->column('modelid')[0];
        $where["modelid"]=$modelid;
        $cat=Db::name("cat")->field("catid,level,name,modelid,status,sort,pid")->where($where)->order("sort asc,catid asc")->select();
        if(count($cat)>0){
            foreach($cat as $v){
                $nbsp_str="";
                for($i=1;$i<$v['level'];$i++){
                    $nbsp_str.="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                }
                $str.="<option value='{$v['catid']}' ".$this_selected.">{$nbsp_str}|-{$v['name']} $disabled_str</option>";
            }
            return $str;
        }else{
            return $str;
        }
    }

    //更新栏目信息数量
    public function updateInfoNum($catid,$table_name){
        $count = Db::name('cms_' . $table_name)->where(array("catid" => $catid))->count();
        Db::name("cat")->update(array(
            "catid" => $catid,
            "infonum" => $count,
        ));

    }

    //cache表数据冗余
    public function cache_redundancy()
    {
        $listRows=Request::param("listRow")?Request::param("listRow"):config("app.page_show_line");//每页显示多少条
        $data = Db::name('cms_cache')
                ->alias('a')
                ->where("a.catid not in(select catid from ".config('database.connections.mysql.prefix')."cat) or a.modelid not in (select modelid from ".config('database.connections.mysql.prefix')."model)")
                ->paginate(['list_rows' => $listRows, 'query' => request()->param()]);
        $newdata = array();
        foreach ($data as $v){
            $catname = Db::name('cat')->where('catid',$v['catid'])->find()['name'];
            if (empty($catname)){
                $v['catname'] = '已不存在';
            }else{
                $v['catname'] = $catname;
            }
            $newdata[] = $v;
        }
        // 获取分页显示
        $pagelist = $data->render();
        View::assign("data", $data);
        View::assign("newdata", $newdata);
        View::assign("pagelist", $pagelist);
        return View::fetch();
    }

    public function cache_redundancy_view()
    {
        $cache_id = Request::param("cache_id");
        $r = Db::name('cms_cache')->where('cache_id',$cache_id)->find();
        $cat = Db::name('cat')->where('catid',$r['catid'])->field('name')->find();
        if ($cat){
            $r['catname'] = $cat['name'];
        }else{
            $r['catname'] = '已不存在';
        }
        View::assign("r", $r);
        return View::fetch();
    }

    public function cache_redundancy_update()
    {
        if(request()->isPost()){
            $data = Request::param();
            $edit['title'] = $data['title'];
            $edit['addtime'] = strtotime($data['addtime']);
            $result = Db::name('cms_cache')->where('cache_id',$data['cache_id'])->save($edit);
            $this->success('修改完成');
        }else{
            $cache_id = Request::param("cache_id");
            $r = Db::name('cms_cache')->where('cache_id',$cache_id)->find();
            View::assign("r", $r);
            return View::fetch();
        }
    }

    //删除冗余数据
    public function cache_redundancy_delete()
    {
        $ids = Request::param('ids');
        if (empty($ids)){
            $this->error('请选择要删除的选项');
        }
        $result = Db::name('cms_cache')->where('cache_id','in',$ids)->delete();
        $this->success("删除成功");
    }

}